const { resolve } = require('path')

const { jgcl } = require(resolve(__dirname, '../../utils/utils'))

const { User } = require(resolve(__dirname, '../../database/dbModule/login'))
const Discuss = require('../../database/dbModule/discuss')

// 添加评论
const addDiscuss = async (ctx) => {
  try {
    const data = ctx.request.body
    const {
      username,
      title,
      discuss,
      auditStatus = true,
      isDel = false
    } = data

    const creatRes = await Discuss.create({
      username,
      title,
      discuss,
      auditStatus,
      isDel
    })
    jgcl(ctx, 200, '添加成功!')
  } catch (err) {
    jgcl(ctx, 2011, '添加失败!', err)
  }
}

// 查询评论
const getDiscuss = async (ctx) => {
  try {
    const data = ctx.query
    const {
      userId,
      title,
    } = data

    const findRes = await Discuss.find({ userId, title, isDel: false })
    if (findRes === null) {
      jgcl(ctx, 2012, '数据不存在!')
    } else {
      jgcl(ctx, 200, '查询成功!', findRes)
    }
  } catch (err) {
    jgcl(ctx, 2014, '查询失败!', err)
    console.log(err)
  }
}
// 查询所有评论
const getDiscussAll = async (ctx) => {
  try {
    const findRes = await Discuss.find({ isDel: false })
    if (findRes.length <= 0) {
      jgcl(ctx, 2012, '数据不存在!')
    } else {
      jgcl(ctx, 200, '查询成功!', findRes)
    }
  } catch (err) {
    jgcl(ctx, 2014, '查询失败!', err)
  }
}

// 删除评论
const delDiscuss = async (ctx) => {
  try {
    const { id } = ctx.request.body
    const findRes = await Discuss.findOne({ _id: id })
    if (findRes !== null) {
      const upRes = await Discuss.updateOne({ _id: id }, { isDel: true })
      jgcl(ctx, 200, '删除成功!', findRes)
    } else {
      jgcl(ctx, 2015, '数据为空!')
    }
  } catch (err) {
    jgcl(ctx, 2016, '删除失败!')
  }
}

module.exports = {
  addDiscuss,
  getDiscuss,
  getDiscussAll,
  delDiscuss,
}